from infra.handler import BaseHandler
from common.internal_random import generate_random_string
import os
class UploadFileHandler(BaseHandler):
    def post(self):
        if 'file' not in self.request.files:
            self.write({'code':404, 'msg': 'No file part in the request'})
            return
        fileinfo = self.request.files['file'][0]
        filename = f"f{generate_random_string(10)}_{fileinfo['filename']}"
        if filename == '':
            self.write({'code':404, 'msg': 'No selected file'})
            return
        if fileinfo:
            upload_path = os.path.join(os.getcwd(), 'uploads')
            if not os.path.exists(upload_path):
                os.makedirs(upload_path)
            file_path = os.path.join(upload_path, filename)
            with open(file_path, 'wb') as f:
                f.write(fileinfo['body'])
            self.write({'code':200, 'msg': 'File successfully uploaded', 'filename': filename})
        else:
            self.write({'code':404, 'msg': 'File type not allowed'})
    
    def get(self):
        filename = self.get_argument('filename', default=None)
        iconname = self.get_argument("iconname", default=None)
  
        if iconname:
            print(iconname)
            if os.path.exists('images'):
                file_path = os.path.join('images', iconname)
                print(file_path)
                if os.path.exists(file_path):
                    with open(file_path, 'rb') as f:
                        self.write(f.read())
                    return
            self.write(f"Filename: {iconname}")
        if(filename):
            print(filename)
            if os.path.exists('uploads'):
                file_path = os.path.join('uploads', filename)
                print(file_path)
                if os.path.exists(file_path):
                    with open(file_path, 'rb') as f:
                        self.write(f.read())
                    return
            self.write(f"Filename: {filename}")
